import axios from 'axios'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.NODE_ENV === 'production' ? process.env.VUE_APP_BASE_API : 'http://localhost:8000/', // api 的 base_url
  timeout: 1200000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    config.headers['Content-Type'] = 'application/json'
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    const code = response.status
    if (code < 200 || code > 300) {
       alert(response.message)
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    let code = 0
    try {
      code = error.response.data.status
    } catch (e) {
      if (error.toString().indexOf('Error: timeout') !== -1) {
          alert('网络请求超时')
          return Promise.reject(error)
      }
    }
    if (code) {
        const errorMsg = error.response.data.message
        if (errorMsg !== undefined) {
          alert(errorMsg)
        }
    } else {
      alert("接口请求失败")
    }
    return Promise.reject(error)
  }
)
export default service
